package com.num2.service.lkw;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import com.num2.dao.lkw.ITransferDao;
import com.num2.form.lkw.Deposit_Money;
import com.num2.form.lkw.Withdraw_Money;
import com.num2.form.xjg.LoginForm;

@Service
public class TransferService {
	@Resource
	private SqlSessionFactory sqlSessionFactory;
	public boolean transMoney(Deposit_Money dm,Withdraw_Money wm,HttpSession session ) {
		//打开session
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过 注解 获取 接口实现类的对象
        ITransferDao transferdao = sqlSession.getMapper(ITransferDao.class);
        
        //如果进账用户和出账用户相同,则转账失败
	    if(((String) session.getAttribute("user_name")).equals(dm.getUser_name())){
	   	   return false;
	    }
	    
	    //通过session得到的username获取user_id
	       int userId = transferdao.selectName((String) session.getAttribute("user_name"));
	       wm.setUser_id(userId);
        
        //通过user_id获取余额balance
        int balanc= transferdao.selectId(wm.getUser_id());
        //将获取的转账金额转变为字符串数组,判断是否每个字符都为数字
        char num[] = wm.getIncome_expend().substring(1).toCharArray();
        for(int i=0;i<num.length;i++){
   			if(!Character.isDigit(num[i])){
   			    return false;
   			}
          }
        char num1[] = dm.getIncome_expend().substring(1).toCharArray();
        for(int i=0;i<num1.length;i++){
   			if(!Character.isDigit(num1[i])){
   			    return false;
   			}
          }
          //若余额小于取款金额，则取款失败
          if(balanc<Integer.parseInt(wm.getIncome_expend().substring(1))){
       	   return false;
          }
	       wm.setBalance(balanc);
	       
//	       System.out.println(balanc);
	     //增加一条出账人出账的记录
	       transferdao.delete(wm);
	       
//	       int a=1/0;
	       
	       //通过jsp页面传输得到的username获取user_id
	       int userid = transferdao.selectNm(dm.getUser_name());
	       dm.setUser_id(userid);
	       
	       //通过user_id获取余额balance
	       int balan= transferdao.selectid(dm.getUser_id());
	       dm.setBalance(balan);
//		   System.out.println(balan);
	       
		   //增加一条用户存款的记录
	       transferdao.add(dm);
	       //提交session
		   sqlSession.commit();
		return true;
	}
	


	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}	
}